<!DOCTYPE html>












  


<html class="theme-next mist use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
































<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=6.6.0" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.6.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/avatar.jpg?v=6.6.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/avatar.jpg?v=6.6.0">


  <link rel="mask-icon" href="/images/logo.svg?v=6.6.0" color="#222">









<script id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '6.6.0',
    sidebar: {"position":"left","display":"hide","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="Spring MVC是主流的MVC框架之一，可以无侵入的和Spring集成，使用起来极为方便，使用@PathVariable @RequestBody等注解自动帮我们处理请求参数，极大的减少了开发者的工作量，本文通过源码分析Spring MVC是如何处理这些注解的。 Spring MVC通过DispatcherServlet接到请求后，经过一系列的处理后（该过程不在本文讨论范围，故不在叙述，具体可">
<meta name="keywords" content="源码分析,Spring MVC,Spring">
<meta property="og:type" content="article">
<meta property="og:title" content="Spring MVC如何处理RequestMapping方法中的请求参数">
<meta property="og:url" content="http://yoursite.com/2018/06/24/Spring MVC如何处理RequestMapping方法中的请求参数/index.html">
<meta property="og:site_name" content="isunimp">
<meta property="og:description" content="Spring MVC是主流的MVC框架之一，可以无侵入的和Spring集成，使用起来极为方便，使用@PathVariable @RequestBody等注解自动帮我们处理请求参数，极大的减少了开发者的工作量，本文通过源码分析Spring MVC是如何处理这些注解的。 Spring MVC通过DispatcherServlet接到请求后，经过一系列的处理后（该过程不在本文讨论范围，故不在叙述，具体可">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2019-03-18T12:10:34.047Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Spring MVC如何处理RequestMapping方法中的请求参数">
<meta name="twitter:description" content="Spring MVC是主流的MVC框架之一，可以无侵入的和Spring集成，使用起来极为方便，使用@PathVariable @RequestBody等注解自动帮我们处理请求参数，极大的减少了开发者的工作量，本文通过源码分析Spring MVC是如何处理这些注解的。 Spring MVC通过DispatcherServlet接到请求后，经过一系列的处理后（该过程不在本文讨论范围，故不在叙述，具体可">






  <link rel="canonical" href="http://yoursite.com/2018/06/24/Spring MVC如何处理RequestMapping方法中的请求参数/">



<script id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>Spring MVC如何处理RequestMapping方法中的请求参数 | isunimp</title>
  












  <noscript>
  <style>
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion .logo-line-before i { left: initial; }
    .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">isunimp</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <p class="site-subtitle">isunimp</p>
      
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">

    
    
    
      
    

    

    <a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">

    
    
    
      
    

    

    <a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-about">

    
    
    
      
    

    

    <a href="/about/" rel="section"><i class="menu-item-icon fa fa-fw fa-user"></i> <br>关于</a>

  </li>

      
      
    </ul>
  

  
    

  

  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2018/06/24/Spring MVC如何处理RequestMapping方法中的请求参数/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="isunimp">
      <meta itemprop="description" content="涉猎广泛，不亦乐乎，不求甚解。">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="isunimp">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Spring MVC如何处理RequestMapping方法中的请求参数

              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2018-06-24 10:18:20" itemprop="dateCreated datePublished" datetime="2018-06-24T10:18:20+08:00">2018-06-24</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2019-03-18 20:10:34" itemprop="dateModified" datetime="2019-03-18T20:10:34+08:00">2019-03-18</time>
              
            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing"><a href="/categories/Spring/" itemprop="url" rel="index"><span itemprop="name">Spring</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>Spring MVC是主流的MVC框架之一，可以无侵入的和Spring集成，使用起来极为方便，使用<code>@PathVariable</code> <code>@RequestBody</code>等注解自动帮我们处理请求参数，极大的减少了开发者的工作量，本文通过源码分析Spring MVC是如何处理这些注解的。</p>
<p>Spring MVC通过<code>DispatcherServlet</code>接到请求后，经过一系列的处理后（该过程不在本文讨论范围，故不在叙述，具体可自行Google，或参考<a href="https://segmentfault.com/a/1190000013816079" target="_blank" rel="noopener">Spring MVC流程解析</a>），找到该请求对应的Controller以及方法后，将这次方法的调用封装成一个<a href="https://github.com/spring-projects/spring-framework/blob/v5.1.2.RELEASE/spring-web/src/main/java/org/springframework/web/method/HandlerMethod.java" target="_blank" rel="noopener">HandlerMethod</a>对象。</p>
<h4 id="参数处理过程"><a href="#参数处理过程" class="headerlink" title="参数处理过程"></a>参数处理过程</h4><p><a href="https://github.com/spring-projects/spring-framework/blob/v5.1.2.RELEASE/spring-web/src/main/java/org/springframework/web/method/support/InvocableHandlerMethod.java#L151-L185" target="_blank" rel="noopener">getMethodArgumentValues</a>就是处理方法参数的核心代码（我是通过打断点一步步找到的0.0）<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// org.springframework.web.method.support.InvocableHandlerMethod </span></span><br><span class="line"><span class="keyword">private</span> Object[] getMethodArgumentValues(NativeWebRequest request, <span class="meta">@Nullable</span> ModelAndViewContainer mavContainer, Object... providedArgs) <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">    <span class="comment">// InvocableHandlerMethod继承自HandlerMethod</span></span><br><span class="line">    <span class="comment">// 获取方法的所有参数</span></span><br><span class="line">    MethodParameter[] parameters = <span class="keyword">this</span>.getMethodParameters();</span><br><span class="line">    Object[] args = <span class="keyword">new</span> Object[parameters.length];</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 遍历处理所有参数</span></span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; parameters.length; ++i) &#123;</span><br><span class="line">        MethodParameter parameter = parameters[i];</span><br><span class="line">        parameter.initParameterNameDiscovery(<span class="keyword">this</span>.parameterNameDiscoverer);</span><br><span class="line">        args[i] = <span class="keyword">this</span>.resolveProvidedArgument(parameter, providedArgs);</span><br><span class="line">        <span class="keyword">if</span> (args[i] == <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="comment">// 根据方法名猜测是检查是否支持parameter的处理</span></span><br><span class="line">            <span class="comment">// 注意argumentResolvers</span></span><br><span class="line">            <span class="keyword">if</span> (<span class="keyword">this</span>.argumentResolvers.supportsParameter(parameter)) &#123;</span><br><span class="line">                <span class="keyword">try</span> &#123;</span><br><span class="line">                    <span class="comment">// 处理参数 </span></span><br><span class="line">                    args[i] = <span class="keyword">this</span>.argumentResolvers.resolveArgument(parameter, mavContainer, request, <span class="keyword">this</span>.dataBinderFactory);</span><br><span class="line">                &#125; <span class="keyword">catch</span> (Exception var9) &#123;</span><br><span class="line">                    <span class="keyword">if</span> (<span class="keyword">this</span>.logger.isDebugEnabled()) &#123;</span><br><span class="line">                        <span class="keyword">this</span>.logger.debug(<span class="keyword">this</span>.getArgumentResolutionErrorMessage(<span class="string">"Failed to resolve"</span>, i), var9);</span><br><span class="line">                    &#125;</span><br><span class="line">                    <span class="keyword">throw</span> var9;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125; <span class="keyword">else</span> <span class="keyword">if</span> (args[i] == <span class="keyword">null</span>) &#123;</span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> IllegalStateException(<span class="string">"Could not resolve method parameter at index "</span> + parameter.getParameterIndex() + <span class="string">" in "</span> + parameter.getExecutable().toGenericString() + <span class="string">": "</span> + <span class="keyword">this</span>.getArgumentResolutionErrorMessage(<span class="string">"No suitable resolver for"</span>, i));</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> args;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>到这里可以看出是由<a href="https://github.com/spring-projects/spring-framework/blob/v5.1.2.RELEASE/spring-web/src/main/java/org/springframework/web/method/support/InvocableHandlerMethod.java#L56" target="_blank" rel="noopener">argumentResolvers</a>间接提供了参数的处理，argumentResolvers是一个<a href="https://github.com/spring-projects/spring-framework/blob/v5.1.2.RELEASE/spring-web/src/main/java/org/springframework/web/method/support/HandlerMethodArgumentResolverComposite.java" target="_blank" rel="noopener">HandlerMethodArgumentResolverComposite</a>对象</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 最重要的一个属性</span></span><br><span class="line"><span class="comment">// 存储了所有参数处理器</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> List&lt;HandlerMethodArgumentResolver&gt; argumentResolvers = <span class="keyword">new</span> LinkedList();</span><br><span class="line"></span><br><span class="line"><span class="comment">// 添加处理器</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> HandlerMethodArgumentResolverComposite <span class="title">addResolver</span><span class="params">(HandlerMethodArgumentResolver resolver)</span></span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.argumentResolvers.add(resolver);</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">this</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 添加处理器</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> HandlerMethodArgumentResolverComposite <span class="title">addResolvers</span><span class="params">(@Nullable HandlerMethodArgumentResolver... resolvers)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (resolvers != <span class="keyword">null</span>) &#123;</span><br><span class="line">    <span class="keyword">for</span> (HandlerMethodArgumentResolver resolver : resolvers) &#123;</span><br><span class="line">    	<span class="keyword">this</span>.argumentResolvers.add(resolver);</span><br><span class="line">    	&#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">this</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 添加处理器</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> HandlerMethodArgumentResolverComposite <span class="title">addResolvers</span><span class="params">(@Nullable List&lt;? extends HandlerMethodArgumentResolver&gt; resolvers)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (resolvers != <span class="keyword">null</span>) &#123;</span><br><span class="line">	    <span class="keyword">for</span> (HandlerMethodArgumentResolver resolver : resolvers) &#123;</span><br><span class="line">    	    <span class="keyword">this</span>.argumentResolvers.add(resolver);</span><br><span class="line">    	&#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">this</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这些处理器都是<a href="https://github.com/spring-projects/spring-framework/blob/v5.1.2.RELEASE/spring-web/src/main/java/org/springframework/web/method/support/HandlerMethodArgumentResolver.java" target="_blank" rel="noopener">HandlerMethodArgumentResolver</a>接口对象，</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">HandlerMethodArgumentResolver</span> </span>&#123;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 检查是否支持参数</span></span><br><span class="line">    <span class="function"><span class="keyword">boolean</span> <span class="title">supportsParameter</span><span class="params">(MethodParameter parameter)</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 处理参数</span></span><br><span class="line">    <span class="meta">@Nullable</span></span><br><span class="line">    <span class="function">Object <span class="title">resolveArgument</span><span class="params">(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory)</span> <span class="keyword">throws</span> Exception</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>但<code>HandlerMethodArgumentResolverComposite</code>本身也实现了这个接口，所以前面的<code>getMethodArgumentValues</code>方法里面可以直接调用<code>supportsParameter</code>,<code>resolveArgument</code>。</p>
<p><code>HandlerMethodArgumentResolverComposite</code>对<code>HandlerMethodArgumentResolver</code>接口的实现如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">supportsParameter</span><span class="params">(MethodParameter parameter)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">this</span>.getArgumentResolver(parameter) != <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> Object <span class="title">resolveArgument</span><span class="params">(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer, NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    <span class="comment">// 获取解析器</span></span><br><span class="line">    HandlerMethodArgumentResolver resolver = <span class="keyword">this</span>.getArgumentResolver(parameter);</span><br><span class="line">    <span class="keyword">if</span> (resolver == <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">"Unknown parameter type ["</span> + parameter.getParameterType().getName() + <span class="string">"]"</span>);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="comment">// 解析参数</span></span><br><span class="line">        <span class="keyword">return</span> resolver.resolveArgument(parameter, mavContainer, webRequest, binderFactory);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> *  获取对应的解析器</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> HandlerMethodArgumentResolver <span class="title">getArgumentResolver</span><span class="params">(MethodParameter parameter)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 从缓存中获取</span></span><br><span class="line">    HandlerMethodArgumentResolver result = (HandlerMethodArgumentResolver)<span class="keyword">this</span>.argumentResolverCache.get(parameter);</span><br><span class="line">    <span class="keyword">if</span> (result == <span class="keyword">null</span>) &#123;</span><br><span class="line">        Iterator var3 = <span class="keyword">this</span>.argumentResolvers.iterator();</span><br><span class="line">        <span class="keyword">while</span>(var3.hasNext()) &#123;</span><br><span class="line">            <span class="comment">// 遍历所有处理器</span></span><br><span class="line">            HandlerMethodArgumentResolver methodArgumentResolver = (HandlerMethodArgumentResolver)var3.next();</span><br><span class="line">            <span class="keyword">if</span> (<span class="keyword">this</span>.logger.isTraceEnabled()) &#123;</span><br><span class="line">                <span class="keyword">this</span>.logger.trace(<span class="string">"Testing if argument resolver ["</span> + methodArgumentResolver + <span class="string">"] supports ["</span> + parameter.getGenericParameterType() + <span class="string">"]"</span>);</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">           <span class="keyword">if</span> (methodArgumentResolver.supportsParameter(parameter)) &#123;</span><br><span class="line">                result = methodArgumentResolver;</span><br><span class="line">                <span class="keyword">this</span>.argumentResolverCache.put(parameter, methodArgumentResolver);</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> result;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="处理器的实现"><a href="#处理器的实现" class="headerlink" title="处理器的实现"></a>处理器的实现</h4><p>到这里处理过程已经基本清楚了，不明白的小伙伴跟着代码多看两遍。现在要弄清楚Spring MVC何时往<code>HandlerMethodArgumentResolverComposite</code>里添加这些处理器的。</p>
<p>Spring MVC为请求匹配Controller以及对应的方法有一个很重要的类<a href="https://github.com/spring-projects/spring-framework/blob/v5.1.2.RELEASE/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerAdapter.java" target="_blank" rel="noopener">RequestMappingHandlerAdapter</a>，该类实现了<code>InitializingBean</code>接口:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// InitializingBean接口实现</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">afterPropertiesSet</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.initControllerAdviceCache();</span><br><span class="line">    List handlers;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.argumentResolvers == <span class="keyword">null</span>) &#123;</span><br><span class="line">        handlers = <span class="keyword">this</span>.getDefaultArgumentResolvers();</span><br><span class="line">        <span class="comment">// 看这里O.O</span></span><br><span class="line">        <span class="keyword">this</span>.argumentResolvers = (<span class="keyword">new</span> HandlerMethodArgumentResolverComposite()).addResolvers(handlers);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.initBinderArgumentResolvers == <span class="keyword">null</span>) &#123;</span><br><span class="line">        handlers = <span class="keyword">this</span>.getDefaultInitBinderArgumentResolvers();</span><br><span class="line">        <span class="keyword">this</span>.initBinderArgumentResolvers = (<span class="keyword">new</span> HandlerMethodArgumentResolverComposite()).addResolvers(handlers);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.returnValueHandlers == <span class="keyword">null</span>) &#123;</span><br><span class="line">        handlers = <span class="keyword">this</span>.getDefaultReturnValueHandlers();</span><br><span class="line">        <span class="keyword">this</span>.returnValueHandlers = (<span class="keyword">new</span> HandlerMethodReturnValueHandlerComposite()).addHandlers(handlers);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 自带了很多参数处理器</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> List&lt;HandlerMethodArgumentResolver&gt; <span class="title">getDefaultArgumentResolvers</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    List&lt;HandlerMethodArgumentResolver&gt; resolvers = <span class="keyword">new</span> ArrayList();</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> RequestParamMethodArgumentResolver(<span class="keyword">this</span>.getBeanFactory(), <span class="keyword">false</span>));</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> RequestParamMapMethodArgumentResolver());</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> PathVariableMethodArgumentResolver());</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> PathVariableMapMethodArgumentResolver());</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> MatrixVariableMethodArgumentResolver());</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> MatrixVariableMapMethodArgumentResolver());</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> ServletModelAttributeMethodProcessor(<span class="keyword">false</span>));</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> RequestResponseBodyMethodProcessor(<span class="keyword">this</span>.getMessageConverters(), <span class="keyword">this</span>.requestResponseBodyAdvice));</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> RequestPartMethodArgumentResolver(<span class="keyword">this</span>.getMessageConverters(), <span class="keyword">this</span>.requestResponseBodyAdvice));</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> RequestHeaderMethodArgumentResolver(<span class="keyword">this</span>.getBeanFactory()));</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> RequestHeaderMapMethodArgumentResolver());</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> ServletCookieValueMethodArgumentResolver(<span class="keyword">this</span>.getBeanFactory()));</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> ExpressionValueMethodArgumentResolver(<span class="keyword">this</span>.getBeanFactory()));</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> SessionAttributeMethodArgumentResolver());</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> RequestAttributeMethodArgumentResolver());</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> ServletRequestMethodArgumentResolver());</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> ServletResponseMethodArgumentResolver());</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> HttpEntityMethodProcessor(<span class="keyword">this</span>.getMessageConverters(), <span class="keyword">this</span>.requestResponseBodyAdvice));</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> RedirectAttributesMethodArgumentResolver());</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> ModelMethodProcessor());</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> MapMethodProcessor());</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> ErrorsMethodArgumentResolver());</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> SessionStatusMethodArgumentResolver());</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> UriComponentsBuilderMethodArgumentResolver());</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.getCustomArgumentResolvers() != <span class="keyword">null</span>) &#123;</span><br><span class="line">        resolvers.addAll(<span class="keyword">this</span>.getCustomArgumentResolvers());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    resolvers.add(<span class="keyword">new</span> RequestParamMethodArgumentResolver(<span class="keyword">this</span>.getBeanFactory(), <span class="keyword">true</span>));</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> ServletModelAttributeMethodProcessor(<span class="keyword">true</span>));</span><br><span class="line">    <span class="keyword">return</span> resolvers;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在程序启动创建这个Bean的时候创建了一批参数处理器，看一下<a href="https://github.com/spring-projects/spring-framework/blob/v5.1.2.RELEASE/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyMethodProcessor.java" target="_blank" rel="noopener">RequestResponseBodyMethodProcessor</a>的supportsParameter方法实现<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">supportsParameter</span><span class="params">(MethodParameter parameter)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 检查这个参数是否有RequestBody注解</span></span><br><span class="line">    <span class="keyword">return</span> parameter.hasParameterAnnotation(RequestBody.class);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>就是我们熟知的<code>@RequestBody</code>注解，有兴趣的可以去看一下<code>resolveArgument</code>方法实现的解析过程，以及其他解析器的实现。</p>
<h4 id="自定义参数处理器"><a href="#自定义参数处理器" class="headerlink" title="自定义参数处理器"></a>自定义参数处理器</h4><p>我们可以实现<code>HandlerMethodArgumentResolver</code>接口来自定义处理器，例如读取Cookie或者Header构造一些信息<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">supportsParameter</span><span class="params">(MethodParameter methodParameter)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (methodParameter.getParameterAnnotation(某注解.class) != <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> Object <span class="title">resolveArgument</span><span class="params">(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory)</span><span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    HttpServletRequest request = (HttpServletRequest) nativeWebRequest.getNativeRequest();</span><br><span class="line">    Object obj = request.getHeader(<span class="string">"xxx_header"</span>);</span><br><span class="line">    <span class="comment">// do...</span></span><br><span class="line">    <span class="keyword">return</span> obj;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>（全文完）</p>

      
    </div>

    

    
    
    

    

    
      
    
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/源码分析/" rel="tag"># 源码分析</a>
          
            <a href="/tags/Spring-MVC/" rel="tag"># Spring MVC</a>
          
            <a href="/tags/Spring/" rel="tag"># Spring</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/03/19/HikariCP源码深度解读（一）/" rel="prev" title="HikariCP源码深度解读（一）">
                HikariCP源码深度解读（一） <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/avatar.jpg" alt="isunimp">
            
              <p class="site-author-name" itemprop="name">isunimp</p>
              <p class="site-description motion-element" itemprop="description">涉猎广泛，不亦乐乎，不求甚解。</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">3</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">2</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">5</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://github.com/isunimp" title="GitHub &rarr; https://github.com/isunimp" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="mailto:ansheck@163.com" title="E-Mail &rarr; mailto:ansheck@163.com" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                </span>
              
            </div>
          

          

          
          

          
            
          
          

        </div>
      </div>

      
      <!--noindex-->
        <div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-4"><a class="nav-link" href="#参数处理过程"><span class="nav-number">1.</span> <span class="nav-text">参数处理过程</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#处理器的实现"><span class="nav-number">2.</span> <span class="nav-text">处理器的实现</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#自定义参数处理器"><span class="nav-number">3.</span> <span class="nav-text">自定义参数处理器</span></a></li></ol></div>
            

          </div>
        </div>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2017 – <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">isunimp</span>

  

  
</div>


  <div class="powered-by">由 <a href="https://hexo.io" class="theme-link" rel="noopener" target="_blank">Hexo</a> 强力驱动 v3.8.0</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 – <a href="https://theme-next.org" class="theme-link" rel="noopener" target="_blank">NexT.Mist</a> v6.6.0</div>




        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

    

    
  </div>

  

<script>
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  
    <script src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script src="/js/src/utils.js?v=6.6.0"></script>

  <script src="/js/src/motion.js?v=6.6.0"></script>



  
  

  
  <script src="/js/src/scrollspy.js?v=6.6.0"></script>
<script src="/js/src/post-details.js?v=6.6.0"></script>



  


  <script src="/js/src/bootstrap.js?v=6.6.0"></script>



  



  











  





  

  

  

  

  

  
  

  

  

  

  

  

  

</body>
</html>
